package com.duowan.cms.service.article.util;

import java.util.Date;

import org.apache.log4j.Logger;

import com.duowan.cms.common.exception.BaseCheckedException;
import com.duowan.cms.common.service.DoToDtoConvertorFactory;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.common.util.ThreadUtil;
import com.duowan.cms.common.webapp.content.SpringApplicationContextHolder;
import com.duowan.cms.domain.article.Article;
import com.duowan.cms.domain.article.ArticleGameLib;
import com.duowan.cms.domain.article.rpst.ArticleGameLibRepository;
import com.duowan.cms.domain.article.rpst.ArticleRepository;
import com.duowan.cms.domain.channel.Channel;
import com.duowan.cms.dto.article.Article4TagListInfo;
import com.duowan.cms.dto.article.ArticleInfo;
import com.duowan.cms.dto.article.ArticleStatus;
import com.duowan.cms.intf.gamelib.GameLibRemoteService;
import com.duowan.cms.intf.wap.WapRemoteService;
import com.duowan.cms.parser.rmi.client.template.TemplateParserRemoteService;
import com.duowan.cms.service.article.Article4TagListService;

public class ArticlePublisher {

    private static Logger logger = Logger.getLogger(ArticlePublisher.class);
    
    private static ArticlePublisher articlePublisher ;

    public static ArticlePublisher getInstance() {
        if (articlePublisher != null) {
            return articlePublisher;
        }
        return new ArticlePublisher();
    }

    /**
     * 预定发布:预定发布只是简单插入数据库， 不作其他同步等操作
     */
    public void reservePublish(ArticleInfo articleInfo) {
    	articleInfo.setStatus(ArticleStatus.PER_PUBLISH);
    	//将文章的发布时间改为预发布时间
    	if(null != articleInfo.getPrePublishTime())
    	    articleInfo.setPublishTime(articleInfo.getPrePublishTime());
        this.saveOrUpdateArticle(articleInfo);
        this.asynParseArticleAndGenerateFile(articleInfo);
    }

    /**
     * 文章初始化（或者更新）并持久化
     * 
     * @param articleInfo
     */
    private void saveOrUpdateArticle(ArticleInfo articleInfo) {
        String channelId = articleInfo.getChannelInfo().getId();
        ArticleRepository articleRepository = SpringApplicationContextHolder.getBean("articleRepository", ArticleRepository.class);
        Article4TagListService article4TagListService = SpringApplicationContextHolder.getBean("article4TagListService", Article4TagListService.class);
        Article article = articleRepository.getByChannelIdAndArticleId(channelId, articleInfo.getId());
        if (article == null) {
            article = new Article(articleInfo);
            articleRepository.save(article);
            article4TagListService.saveArticle4TagListInfo(articleInfo);
        } else {
            //更新article
            article.update(articleInfo);
            articleRepository.update(article);
            //更新article4TgList
            article4TagListService.updateArticle4TagListInfo(articleInfo);
        }
        logger.info("成功保存文章[channelId=" + channelId + ",articleId=" + articleInfo.getId() + ", articleTitle=" + articleInfo.getTitle() + "]");
    }

    /**
     * 直接发布
     * 
     * @param articleInfo
     */
    public void immediatePublish(ArticleInfo articleInfo) {
    	articleInfo.setStatus(ArticleStatus.NORMAL);
        this.saveOrUpdateArticle(articleInfo);
        this.saveOrUpdateArticleGameLib(articleInfo);
        this.asynParseArticleAndGenerateFile(articleInfo);
        this.asynSend2Wap(articleInfo);
        //this.asynSend2Qa(articleInfo);
        //this.asynSend2Zone(articleInfo);
    }

    /**
     *  生成静态页面，异步实现【模板解析模块实现】 
     */
    private void asynParseArticleAndGenerateFile(final ArticleInfo finalArticleInfo) {
    	

        ThreadUtil.getThreadPool().execute(new Runnable() {
            String channelId = finalArticleInfo.getChannelInfo().getId();
            Long templateId = finalArticleInfo.getTemplateId();
            public void run() {
                try {
                	if (templateId == null) {//没有选中模板，不进行解析
                		logger.info("不解析文章:文章[channelId=" + channelId + ",articleId=" + finalArticleInfo.getId() + ", articleTitle=" + finalArticleInfo.getTitle() + "]没有选中模板");
            			return;
            		}
                    TemplateParserRemoteService parserRemoteService = SpringApplicationContextHolder.getBean("templateParserRemoteService", TemplateParserRemoteService.class);
                    ArticleInfo newArticleInfo = this.getArticleInfo();
                    parserRemoteService.parseArticleAndGenerateFile(newArticleInfo.getChannelInfo(), newArticleInfo);
                    logger.info("成功解析文章，生成文章[channelId=" + channelId + ",articleId=" + finalArticleInfo.getId() + ", articleTitle=" + finalArticleInfo.getTitle() + "]静态页面");
                } catch (Exception e) {
                    logger.error("出现异常，解析文章[channelId=" + channelId + ",articleId=" + finalArticleInfo.getId() + ", articleTitle=" + finalArticleInfo.getTitle() + "]失败，异常原因：" + e);
                }
            }

            private ArticleInfo getArticleInfo() {
                ArticleRepository articleRepository = SpringApplicationContextHolder.getBean("articleRepository", ArticleRepository.class);
                // 获取保存后的文章
                Article article = articleRepository.getByChannelIdAndArticleId(channelId, finalArticleInfo.getId());
                ArticleInfo newArticleInfo = (ArticleInfo) DoToDtoConvertorFactory.getConvertor(Article.class).do2Dto(article);
                newArticleInfo.setNeedComment(finalArticleInfo.isNeedComment());
                //设置相关游戏
                ArticleGameLibRepository articleGameLibRepository = SpringApplicationContextHolder.getBean("articleGameLibRepository", ArticleGameLibRepository.class);
                ArticleGameLib articleGameLib = articleGameLibRepository.getArticleGameLib(channelId, finalArticleInfo.getId());
                if (articleGameLib != null) {
                    newArticleInfo.setRelateGame(articleGameLib.getRelategame());
                }
                return newArticleInfo;
            }
        });
    }
    
    public void GenerateEmptyLinkFile(final Article4TagListInfo a4tl){
        ThreadUtil.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    if (a4tl != null) {//没有选中模板，不进行解析
                        TemplateParserRemoteService parserRemoteService = SpringApplicationContextHolder.getBean("templateParserRemoteService", TemplateParserRemoteService.class);
                        parserRemoteService.parseEmptyLinkAndGenerateFile(a4tl);
                        logger.info("成功生成文章[channelId=" + a4tl.getChannelInfo().getId() + ",articleId=" + a4tl.getId() + "]空链接静态页面");
                    }
                } catch (Exception e) {
                    logger.error("生成文章[channelId=" + a4tl.getChannelInfo().getId() + ",articleId=" + a4tl.getId() + "]空链接静态页面失败!!原因：", e);
                }
            }

        });
    }

    /**
     *  保存数据到游戏库并且推送到游戏库:
     *  1. 先判断游戏库数据是否已经存在，若数据已经存在，则更新；
     *  2. 若数据已经存在,再判断"相关游戏"是否为空，若相关游戏非空，则插入；若数据不存在，且相关游戏为空,则什么都不做；
     *  达到的效果：
     *  	新增时，"相关游戏"为空，则不插入"相关游戏"的数据库；
     *  	更新时，可以更新"相关游戏"为其他名称，也可以更新相关游戏为空
     */
    private void saveOrUpdateArticleGameLib(ArticleInfo articleInfo) {
        
    	ArticleGameLibRepository articleGameLibRepository = SpringApplicationContextHolder.getBean("articleGameLibRepository", ArticleGameLibRepository.class);
    	ArticleGameLib articleGameLib = this.getArticleGameLib(articleInfo);
    	if(articleGameLibRepository.getArticleGameLib(articleInfo.getChannelInfo().getId() , articleInfo.getId()) != null){
    		articleGameLibRepository.update(articleGameLib);
    	}else if( !StringUtil.isEmpty(articleInfo.getRelateGame()) ){
    		articleGameLibRepository.save(articleGameLib);
    	}

        this.syncGameLib(articleInfo.getRelateGame(), articleInfo.getTitle(), articleInfo.getUrlOnLine()); //同步到游戏库系统
    }
    
    private ArticleGameLib getArticleGameLib(ArticleInfo articleInfo){
    	String channelId = articleInfo.getChannelInfo().getId();
    	ArticleRepository articleRepository = SpringApplicationContextHolder.getBean("articleRepository", ArticleRepository.class);
    	 Article article = articleRepository.getByChannelIdAndArticleId(channelId, articleInfo.getId());
         ArticleGameLib articleGameLib = new ArticleGameLib();
         articleGameLib.setArticle(article);
         articleGameLib.setChannel(new Channel(channelId));
         articleGameLib.setUpdateTime(new Date());
         articleGameLib.setRelategame(articleInfo.getRelateGame());
         return articleGameLib;
    }

    /**
     * 推送到wap 
     */
    private void asynSend2Wap(final ArticleInfo finalArticleInfo) {
        if (finalArticleInfo.isSyncWap()) {
            ThreadUtil.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                   try {
                        WapRemoteService wapRemoteService = SpringApplicationContextHolder.getBean("wapRemoteService", WapRemoteService.class);// wap接口
                        wapRemoteService.sendArticleToWap(finalArticleInfo);
                    } catch (BaseCheckedException e) {
                        logger.error("文章[channelId="+finalArticleInfo.getChannelInfo().getId()+", articleId="+finalArticleInfo.getId()+"]推送到wap失败:", e);
                    }
                }
            });
        }
    }

    /**
     *  同步到Y世界 
     */
    /*private void asynSend2Qa(final ArticleInfo finalArticleInfo) {
        if (finalArticleInfo.isSyncQa()) {
            ThreadUtil.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    QaRemoteService qaRemoteService = SpringApplicationContextHolder.getBean("qaRemoteService", QaRemoteService.class);// Y世界远程调用接口
                    qaRemoteService.publish(finalArticleInfo.getChannelInfo().getId(), finalArticleInfo.getTitle(), finalArticleInfo.getContent());
                }
            });
        }
    }*/

    /**
     *  同步到有爱
     */
    /*private void asynSend2Zone(final ArticleInfo finalArticleInfo) {
        if (finalArticleInfo.isSyncZone()) {
            ThreadUtil.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    ZoneService zoneService = SpringApplicationContextHolder.getBean("zoneService", ZoneService.class);
                    String zoneUserId = finalArticleInfo.getZoneUserId();
                    ZoneUserInfo zoneUserInfo = zoneService.getById(zoneUserId);
                    String userName = zoneUserInfo.getUserName();// 有爱账号用户名
                    String zoneTag = zoneUserInfo.getDefaultTag();// 有爱话题，
                    ZoneRemoteService zoneRemoteService = SpringApplicationContextHolder.getBean("zoneRemoteService", ZoneRemoteService.class);// 有爱远程调用接口
                    try {
                        zoneRemoteService.publish(userName, finalArticleInfo.getUrlOnLine(), finalArticleInfo.getTitle(), zoneTag, finalArticleInfo.getSource(),
                                finalArticleInfo.getAuthor());
                    } catch (BaseCheckedException e) {
                        logger.error("文章[channelId="+finalArticleInfo.getChannelInfo().getId()+", articleId="+finalArticleInfo.getId()+"]同步到有爱失败:", e);
                    }
                }
            });
        }
    }*/
    
    private void syncGameLib(final String gameName, final String articleTitle, final String articleUrl){
        ThreadUtil.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                GameLibRemoteService gameLibRemoteService = SpringApplicationContextHolder.getBean("gameLibRemoteService", GameLibRemoteService.class);
                try {
                    gameLibRemoteService.sendArticle(gameName, articleTitle, articleUrl);
                } catch (BaseCheckedException e) {
                    logger.error("文章[articleTitle="+articleTitle+", articleUrl="+articleUrl+"]推送到游戏库失败:", e);
                }
            }
        });
    }

}
